#pragma once
#include "Socket.hpp"
#include "Log.hpp"
#include <functional>
using func_t = std::function<std::string(std::string &package)>;
class TcpServer
{
public:
    TcpServer(uint16_t port, func_t callback) : port_(port), callback_(callback)
    {
    }
    void InitServer()
    {
        listensock_.Socket();
        listensock_.Bind(port_);
        listensock_.Listen();
        lg(Info, "Socket init...");
    }
    void Start()
    {
        signal(SIGCHLD, SIG_IGN);
        signal(SIGPIPE, SIG_IGN);
        while (true)
        {
            std::string clientip;
            uint16_t clientport;
            int sockfd = listensock_.Accept(&clientip, &clientport);
            if (sockfd < 0)
                continue;
            //
            lg(Info, "Socket accept,sockfd:%d,clientip:%s,clientport:%d", sockfd, clientip.c_str(), clientport);

            if (fork() == 0)
            {
                listensock_.Close();
                std::string inbuff_stream;
                while (true)
                {
                    char buff[128];
                    int n = read(sockfd, buff, sizeof(buff));
                    if (n > 0)
                    {
                        buff[n] = 0;
                        inbuff_stream += buff;
                        lg(Info, "%s", inbuff_stream.c_str());
                        while (true)
                        {
                            std::string inbuff = callback_(inbuff_stream);

                            if (inbuff.empty())
                                break;
                            write(sockfd, inbuff.c_str(), inbuff.size());
                        }
                    }
                    else
                        break;
                }
                exit(0);
            }
            close(sockfd);
        }
    }
    ~TcpServer() {}

private:
    uint16_t port_;
    Sock listensock_;
    func_t callback_;
};